//请求拦截器
const interceptor = {
    invoke(object:any) {
        if(!object.url.includes('http')){
            object.url = baseURL + object.url
        }
        object.header={
            ...object.header,
            'source-client':'miniapp',
            'name':'123'
        }
        const user = useMemberStore()
        const token = user.profile?.token
        if(token){
            object.header.Authorization = token
        }

    }
}

const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
import { useMemberStore } from '@/stores';
uni.addInterceptor('request', interceptor)
uni.addInterceptor('uploadFile', interceptor)


interface Data<T>{
    msg:string,
    result:T,
    code:string
}
export const http = <T>(options:UniApp.RequestOptions) =>{
    return new Promise<Data<T>>((resolve,reject) => {
        uni.request({
            ...options,
            success(res){
                if(res.statusCode>=200 && res.statusCode <= 300){
                    resolve(res.data as Data<T>)
                }else if(res.statusCode ===401 ){
                    const user = useMemberStore()
                    user.clearProfile()
                    uni.redirectTo({ url:"/pages/login/login"})
                    reject(res)
                }else{
                    uni.showToast({
                        icon:'none',
                        title:(res.data as Data<T>).msg || '请求失败'
                    })
                    reject(res)
                }
            },
            fail(){
                uni.showToast({
                    icon:'none',
                    title:'网络错误'
                })
            }
        })
    })
}

